package com.mudrov.realization;

import java.util.NoSuchElementException;

import com.mudrov.collections.realization.ArrayListForQueue;
import com.mudrov.interfaces.Queue;

public class ArrayListQueue<E> extends ArrayListForQueue<E> implements Queue<E>{

	private Integer start = null;
	private Integer end = 0;
	
	@Override
	public E element() {
		if(start == end || start == null)
			throw new NoSuchElementException();
		return arrayOfElements[start];
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean offer(E e) {
		if (size == capacity) {
			E[] newArray = (E[]) (new Object[capacity *= 2]);
			System.arraycopy(arrayOfElements, 0, newArray, 0, size);
			arrayOfElements = newArray;
		}
		++size;
		arrayOfElements[end] = e;
		if(start == null)
			start = end;
		end = (++end)%capacity;
		return true;
	}

	@Override
	public E peek() {
		if(start == end || start == null)
			return null;
		return arrayOfElements[start];
	}

	@Override
	public E poll() {
		if(start == end || start == null)
			return null;
		E toReturn = arrayOfElements[start++];
		start %= capacity;
		if(start == end)
			start = null;
		--size;
		return toReturn;
	}

	@Override
	public E remove() {
		if(start == end || start == null)
			throw new NoSuchElementException();
		E toReturn = arrayOfElements[start++];
		start %= capacity;
		if(start == end)
			start = null;
		--size;
		return toReturn;
	}

}
